package com.ope.web.controller.chainresponsibility;

import cn.hutool.core.lang.Assert;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import javax.annotation.PostConstruct;

import com.ope.web.model.DTO.ProcessMointorRequestBody;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.annotation.AnnotationAwareOrderComparator;
import org.springframework.stereotype.Component;




/**
 * 解码管理类
 * @author  fxr
 * @date 2024年12月24日16:48:17
 */
@Component
@Slf4j
public class TopicDataManager implements ApplicationContextAware {


    private List<TopicAnalysisHandle> decoders = new ArrayList<>();
    private static ApplicationContext context;
    private static TopicAnalysis header;
    //所有产品类型
    private static List<String> hasSingle = Arrays.asList("sppp", "project", "spgd", "weather",
            "business", "nacos", "history", "model", "alarm", "cfcg", "collection",
            "czlpg", "distributed", "etl", "rollout", "govern", "simulator", "smdg");


    /**
     * 初始化
     */
    @PostConstruct
    private void init() {
        Map<String, TopicAnalysisHandle> beansOfType = context.getBeansOfType(TopicAnalysisHandle.class);
        beansOfType.entrySet().forEach(entry -> {
            decoders.add(entry.getValue());
        });
        AnnotationAwareOrderComparator.sort(decoders);
        decoders.forEach(decoder -> {
            add(decoder);
        });
    }

    /**
     *
     * @param processMointorRequestBody processMointorRequestBody
     */
    public void decoder(ProcessMointorRequestBody processMointorRequestBody) {
        Assert.notNull(processMointorRequestBody, "配置为空");
        log.info("header+++++++:{}", header.toString());
        if (header == null) {
            return;
        }
        header.decode(processMointorRequestBody);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.context = applicationContext;
    }


    /**
     *
     * @param productType productType
     * @return  List<String>
     */
    private List<String> parseData(String productType) {
        if (hasSingle.contains(productType)) {
            return hasSingle;
        } else {
            return Arrays.asList(productType);
        }
    }


    /**
     *
     * @param tail tail
     */
    private void add(TopicAnalysis tail) {
        if (header == null) {
            header = tail;
        } else {
            TopicAnalysis current = header;
            TopicAnalysis next = current.getNext();
            while (next != null) {
                current = next;
                next = current.getNext();
            }
            current.setNext(tail);
        }
    }


}
